package com.benshou.bsoa.common.filter;

import com.benshou.bsoa.common.trace.TraceIdContext;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class TraceIdFilter extends OncePerRequestFilter {

    public static final String HEAD_TRACE_ID = "X-TRACE-ID";

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            @NotNull HttpServletResponse response,
            @NotNull FilterChain filterChain
    ) throws ServletException, IOException {
        try {
            // 从请求头获取或生成TraceId
            String traceId = request.getHeader(HEAD_TRACE_ID);
            if (!StringUtils.hasLength(traceId)) {
                traceId = TraceIdContext.generateTraceId();
            }
            TraceIdContext.putTraceId(traceId);

            filterChain.doFilter(request, response);
        } finally {
            TraceIdContext.clearTraceId();
        }
    }
}